import {Component, ViewChild, OnInit, ElementRef, HostListener} from '@angular/core';
import {
    Platform, App, ViewController, Nav, Tabs, Events, AlertController, LoadingController
} from 'ionic-angular';
import {StatusBar} from '@ionic-native/status-bar';
import {SplashScreen} from '@ionic-native/splash-screen';
import {Network} from "@ionic-native/network";
import {PushService} from '../services/native/push/push.service';
import {ScreenOrientation} from "@ionic-native/screen-orientation";
import {Keyboard} from "@ionic-native/keyboard";
import {LoginProvider} from "../providers/login/login";
import {BackButtonService} from "../services/common/back-button.service";
import {PushMsgModel} from '../model/services/native/push/push-msg-model';
import {MessageOverviewPage} from "../pages/information/message-overview/message-overview";
import {AuthService} from "../services/common/auth.service";
import {AdpMenuComponent} from "../components/common/adp-menu/adp-menu.component";
import {HTTP} from "@ionic-native/http";
import {BASEURL, IOSPLISTURL} from "../config/url.config";
import {UnlockService} from '../services/native/authentication/authentication.service';
import {HttpErrorHandlerService} from '../services/common/http-error-handler.service';
import {FileTransfer} from "@ionic-native/file-transfer";
import {LoadingService} from "../services/common/loading.service";
import {File} from "@ionic-native/file";
import {LocalStorageService} from "../services/native/local-storage/local-storage.service";
import {FileService} from "../services/native/file/file.service";
/*import {CaptchaService} from '../services/common/captcha.service';*/
import {ToastService} from "../services/common/toast.service";
import {FileOpener} from "@ionic-native/file-opener";
import {VersionService} from "../services/common/version.service";
import {NetworkService} from "../services/common/network.service";
import {AppVersion} from "@ionic-native/app-version";
import {MobileAccessibility} from "@ionic-native/mobile-accessibility";
import {PermissionsService} from "../services/native/permissions/permissions.service";
import {JPushControlerService} from "../services/native/push/jpush-controler.service";
import {AdpMenuController} from "../components/common/adp-menu/adp-menu.controller";
import {CacheImgService} from "../services/native/cache-img/cache-img.service";
import {LoginPage} from "../pages/login/login";
import {GraphicLoginPage} from "../pages/login/graphic-login/graphic-login";
import {FingerprintLoginPage} from "../pages/login/fingerprint-login/fingerprint-login";

/*declare let JAnalytics;*/
export interface PageInterface {
    title: string;
    name: string;
    icon: string;
    index?: number;
    isTabRoot?: boolean;
}
@Component({
    templateUrl: 'app.html',
    providers: [
        AuthService,
        LoadingService,
        FileService,
        LocalStorageService,
        VersionService,
        NetworkService,
        File,
        FileTransfer,
        FileOpener,
        AppVersion,
        PermissionsService,
        ToastService,
        AdpMenuController
    ]
})
export class MyApp implements OnInit {

    @ViewChild(Nav) nav: Nav;
    @ViewChild(AdpMenuComponent) menu: AdpMenuComponent;
    @ViewChild("captchaModal") captchaModal: ElementRef;
    @ViewChild("versionModal") versionModal: ElementRef;
    @ViewChild("networkModal") networkModal: ElementRef;
    @ViewChild("mycontent") navEl: Nav;

    rootPage: string;
    avatorUrl: string = './assets/images/common/icon_headportrait_default.png';
    nickName: string;
    platformType: string;
    iosAddress: string;
    androidAddress: string;
    versionNum: string;
    isRequiredUpdate: boolean;
    public pages: PageInterface[] = [];
    private showDown = false;
    private showUp = true;

    constructor(private platform: Platform,
                private appCtrl: App,
                public backButtonService: BackButtonService,
                statusBar: StatusBar,
                splashScreen: SplashScreen,
                private network: Network,
                private keyboard: Keyboard,
                private pushService: PushService,
                private loginProvider: LoginProvider,
                private screenOrn: ScreenOrientation,
                private authService: AuthService,
                private unlockService: UnlockService,
             /*   private captchaService: CaptchaService,*/
                private httpErrorHandler: HttpErrorHandlerService,
                private events: Events,
                private LoginPro: LoginProvider,
                private http: HTTP,
                private fileService: FileService,
                private alertCtrl: AlertController,
                private loadingCtrl: LoadingController,
                private toastService: ToastService,
                private opener: FileOpener,
                private versionService: VersionService,
                private networkService:NetworkService,
                private jPushControlerService: JPushControlerService,
                private mobileAccessibility: MobileAccessibility,
                private cacheImg: CacheImgService,
                private menuCtrl: AdpMenuController) {
        platform.ready().then(() => {
            // Okay, so the platform is ready and our plugins are available.
            // Here you can do any higher level native things you might need.

            statusBar.styleDefault();
            this.keyboard.disableScroll(true);
            this.backButtonService.registerBackButtonAction();//注册系统返回键
            this.setDefaultStorage();
            this.pushInit();
            this.setRootPage();
            this.netWatch();
            this.lockOrientation();
            this.lockFontSize();
/*
            if(typeof JAnalytics !== 'undefined') {
                JAnalytics.init();
                JAnalytics.initCrashHandler();
            }*/
            if (platform.is('cordova') && BASEURL.indexOf('https://') !== -1) {
                this.http.enableSSLPinning(true).then(value => {
                    console.log(value, 'enableSSLPinning value');
                }, reason => {
                    console.log(reason, 'enableSSLPinning reason');
                })
            }
            this.vivoFocusShowPaste();
            if (platform.is('cordova')) {
                setTimeout(function () {
                    splashScreen.hide();
                }, 1000);
            }
            this.updateVersion(platform); //暂时注释版本检查
        });
    }

    @HostListener("document:pause")
    onAppPause() {
        this.unlockService.pauseLog();
    }

    @HostListener("document:resume")
    onAppResume() {
        this.jPushControlerService.clearBadge();
        this.unlockService.resumeCheck().then(page => {
           if (page) {
               this.menuCtrl.hideMenu();
               this.navEl.setRoot(page, null, {
                   animate: false
               });
           }
        });
    }

    ngOnInit(): void {
       /* this.captchaService.init(this.captchaModal.nativeElement);*/

        this.versionService.init(this.versionModal.nativeElement);
        this.networkService.init(this.networkModal.nativeElement);
        this.events.subscribe('loginIn', () => {
            this.initAuthInfo();
        });
        this.events.subscribe('menu open', () => {
            this.initAuthInfo();
            this.getUnMessage();
        });
        this.events.subscribe('checkVersion', (res, checkType) => {
            this.showVersion(res, checkType);
        });
        this.events.subscribe('checkNet', (res) => {
            this.checkNet();
        });
        if (localStorage.getItem('roles')) {
            this.initAuthInfo();
        }
    }

    public setDefaultStorage() {
        localStorage.removeItem('ReLoginFlag');//处理kill进程的情况下，ReloginFlag始终未true，导致再次进app时直接进入app。
    }

    //版本更新
    public updateVersion(platform) {
        if (platform.is('ios')) {
            this.platformType = 'IOS';
        } else if (platform.is('android')) {
            this.platformType = 'ANDROID';
        } else {
            this.platformType = '';
            this.versionService.hide();
        }
        if (this.platformType != '') { // androod 和 ios 里面的App才进行版本检查，模拟器忽略
            this.versionService.checkVersion(this.platformType).then(res => {
                res.subscribe(result => {
                    this.showVersion(result, 'autoCheck');
                });
            }).catch(error => {
                console.log("check version error:" + error);
                this.versionService.hide();
            });
        }
    }

    //显示升级页面
    showVersion(versionInfo, checkType) {
        if (versionInfo.upgrade == 'required') {//表示需要升级
            this.isRequiredUpdate = true;
        } else if (versionInfo.upgrade == 'optional') {
            this.isRequiredUpdate = false;
        } else {
            this.isRequiredUpdate = false;
            this.versionService.hide();
        }
        if (versionInfo.upgrade == 'required' || versionInfo.upgrade == 'optional') {
            this.versionNum = versionInfo.version;
            if (this.platformType === 'IOS') {
                this.iosAddress = "itms-services://?action=download-manifest&url=" + IOSPLISTURL;
            }
            if (this.platformType === 'ANDROID') {
                this.androidAddress = versionInfo.downLoadUrl;
            }
            let ignoreVersion = localStorage.getItem("ignoreVersion");
            if (this.versionNum != ignoreVersion || checkType == 'handCheck') { //手动检查更新的时候要显示，最新版本和已忽略的版本不一致也要显示
                this.versionService.show();
            }
        } else {
            this.versionService.hide();
        }
    }

    //更新app
    public updateApp() {
        if (this.platformType === 'IOS') {
            this.versionService.installToIOS(this.iosAddress);
        } else {
            this.versionService.updateApp(this.androidAddress);
        }
    }

    // 暂不更新
    public cancelUpdate() {
        localStorage.setItem("ignoreVersion", this.versionNum);
        this.versionService.hide();
    }

    public initAuthInfo() {
        this.pages = this.authService.getNavMenu();
        let headImage = this.authService.getAuthAvator();
        if (headImage === "null") {
            this.avatorUrl = './assets/images/common/icon_headportrait_default.png';
        }
        else {
            this.fileService.getAzureInfo().subscribe((data) => {
                this.cacheImg.getImgPath(headImage, data.azureInfo)
                    .then((res) => {
                        this.avatorUrl = res;
                    });
                // this.avatorUrl = this.fileService.getCompletePath(headImage, data.azureInfo);
            });
        }
        this.nickName = this.authService.getAuthName();
    }

    public getUnMessage() {
        let index = this.pages.findIndex((item) => {
            return item.name === 'MessageOverviewPage';
        });
        this.LoginPro.hasUnMessage().subscribe((res) => {
            if (res && index !== -1) {
                this.pages[index].icon = 'un-message';
            } else {
                this.pages[index].icon = 'menu_message';
            }
        });
    }

    netWatch() {
        this.checkNet();
        this.network.onConnect().subscribe(() => { //监听联网
            console.log('network connected!');
            this.networkService.hideNetWorkError();
            // We just got a connection but we need to wait briefly
            // before we determine the connection type. Might need to wait.
            // prior to doing any api requests as well.
            setTimeout(() => {
                console.log(this.network);
                if (localStorage.getItem('stopPush') && localStorage.getItem('stopPush') === 'fail') {
                    this.jPushControlerService.setAliasNull()
                }
            }, 3000);
        });
        this.network.onDisconnect().subscribe(() => { //监听断网
            console.log('network was disconnected :-(');
            this.networkService.showNetWorkError();
        });

    }

    private pushInit() {
        this.pushService.openNotification((msg: PushMsgModel) => {
            let currentView: ViewController = null;

            let navCtrl = this.appCtrl.getActiveNavs()[0];
            let views = navCtrl._views;
            currentView = views[views.length - 1];
            //      console.log(`${currentView ? currentView.id : null}==onNotification:${JSON.stringify(msg)}`);
            this.pushService.pushToOpenPage(msg, currentView, (viewName, opts, done) => {
                navCtrl.push(viewName, opts, done)
            });
        });
    }

    //设置根路径
    private setRootPage() {
        this.unlockService.getDisplayPage().then(page => {
            console.log('setRootPage', page);
            if(this.checkRootPage(page)){
                this.rootPage = page;
            }
        });
    }
    private checkNet(){
        this.networkService.checkNetWork();
    }
    private refreshToken() {
        this.unlockService.refresh();
        //this.loginProvider.refreshToken();
    }

    /**
     * 锁定竖屏设置
     * 参数说明： 'portrait-primary': 主竖屏
     */
    private lockOrientation(): void {
        this.screenOrn.lock(this.screenOrn.ORIENTATIONS.PORTRAIT)
            .then(() => {
            }).catch((e) => {
        });
    }

    /**
     * 判断侧边栏目前高亮
     * @param {PageInterface} page
     * @returns {boolean}
     */
    isActive(page: PageInterface) {
        let childNav = this.nav.getActiveChildNavs()[0];
        if (childNav && childNav.getActiveChildNavs()) {
            if (childNav.getActiveChildNavs()[0]) {
                let views = childNav.getActiveChildNavs()[0]._views;
                let currentView = views[views.length - 1];
                if (currentView.name === 'TeamTeamIncreasePage') {
                    if (currentView.instance.overView == '1') {
                        return false;
                    }
                }
                return currentView.name === page.name;
            }
        }
        return false;
    }

    //侧边栏跳转
    pageTo(page: PageInterface, index) {
        if (this.nav.getActiveChildNavs().length && index != undefined) {
            let tabs = this.nav.getActiveChildNavs()[0] as Tabs;
            //如果在tab的二级页面 先回退值tab
            if (tabs.getSelected()) {
                tabs.getSelected().popToRoot({animate: false});
            }
            //更新到目标页面所在的Tab页面
            tabs.select(index).then(() => {
                //目标页面如果不是1级页面再push
                if (!page.isTabRoot) {
                    tabs.getSelected().push(page.name, {}, {animate: false});
                }
            }).catch((err) => {
                //   console.log(err);
            });
        }
        this.menu.hideMenu();
    }

    logout() {
        this.menu.hideMenu();
        this.unlockService.lockout(true);
        this.jPushControlerService.setAliasNull();
    }

    // vivo X9手机聚焦后input、textarea输入框touchmove后无法显示复制\粘贴的bug
    vivoFocusShowPaste() {
        window.addEventListener('touchmove', (e) => {
            if ((e.target['tagName'] == 'INPUT' || e.target['tagName'] == 'TEXTAREA' || (e.target['className'] == 'input-cover' && e.target['tagName'] == 'DIV')) && navigator.userAgent.indexOf('vivo X9') > -1) {
                //console.log('vivo X9')
                e.stopPropagation();
                e.preventDefault();
            }
        })
    }

    onScroll(e) {
        if (e.scrollTop < 10) {
            this.showDown = false;
        } else {
            this.showDown = true;
        }
        let content = document.querySelector('adp-menu .scroll-content');
        let distance = content.scrollHeight - content.clientHeight;

        if (distance - e.scrollTop > 10) {
            this.showUp = true;
        } else {
            this.showUp = false;
        }
    }

    /**
     * 锁定字体大小不随系统字体大小调整改变
     */
    lockFontSize() {
        this.mobileAccessibility.usePreferredTextZoom(false);
    }
    /**
     * 隐藏网络异常
     */
    hideNetWorkError(){
        this.networkService.hideNetWorkError();
    }
    checkRootPage(Page){
        let _location = window.location.hash;
        if((Page == "LoginPage" && _location.indexOf('/login')>-1)||
            (Page == "GraphicLoginPage" && _location.indexOf('/graphic-login')>-1)||
            (Page == "GraphicLoginPage" && _location.indexOf('/login')>-1)||
            (Page == "FingerprintLoginPage" && _location.indexOf('/fingerprint-login')>-1)||
            (Page == "FingerprintLoginPage" && _location.indexOf('/login')>-1)){
            return false;
        }else{
            return true;
        }
    }
}

